{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "pygame 1.9.6\n",
      "Hello from the pygame community. https://www.pygame.org/contribute.html\n"
     ]
    },
    {
     "ename": "SystemExit",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "An exception has occurred, use %tb to see the full traceback.\n",
      "\u001b[1;31mSystemExit\u001b[0m\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\joaovitor\\anaconda3\\lib\\site-packages\\IPython\\core\\interactiveshell.py:3351: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.\n",
      "  warn(\"To exit: use 'exit', 'quit', or Ctrl-D.\", stacklevel=1)\n"
     ]
    }
   ],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import joblib\n",
    "import pygame\n",
    "from sys import exit\n",
    "from random import randrange, choice\n",
    "import os\n",
    "\n",
    "jump_model = joblib.load('jump_model.pkl')\n",
    "msg = ''\n",
    "\n",
    "def convert_frame_to_model(Canny_image):\n",
    "    '''\n",
    "    1° step = resize the image to (height=96, width=128) \n",
    "    2° step = reshape the image to (-1, img.size)\n",
    "    3° step = give the image to the model\n",
    "    '''\n",
    "    #1° Step\n",
    "    width = 128\n",
    "    height = 96\n",
    "    dim = (width, height)\n",
    "    resized = cv2.resize(Canny_image, dim, interpolation = cv2.INTER_AREA)\n",
    "    \n",
    "    #2° Step\n",
    "    reshaped_image = resized.reshape(-1, resized.size)\n",
    "    \n",
    "    #3° Step\n",
    "    return jump_model.predict(reshaped_image)\n",
    "    \n",
    "cap = cv2.VideoCapture(0)\n",
    "\n",
    "\n",
    "x = 800 #500\n",
    "y = 700 #400\n",
    "\n",
    "os.environ['SDL_VIDEO_WINDOW_POS'] = f'{(x, y)}'\n",
    "\n",
    "#os.environ['SDL_VIDEO_CENTERED'] = '0'\n",
    "\n",
    "THIS_FOLDER = os.getcwd()\n",
    "\n",
    "pygame.init()\n",
    "\n",
    "SCREEN_WIDTH = 840\n",
    "SCREEN_HEIGHT = 680\n",
    "\n",
    "WHITE = (255,255,255)\n",
    "BLACK = (0,0,0)\n",
    "\n",
    "FPS = 30\n",
    "GAME_SPEED = 10\n",
    "FLOOR_SPEED = 10\n",
    "GAME_OVER = False\n",
    "\n",
    "points = 0\n",
    "screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n",
    "\n",
    "song = 0\n",
    "\n",
    "font = pygame.font.SysFont('comicsansms', 40, True, True)\n",
    "score_sound = pygame.mixer.Sound(os.path.join(THIS_FOLDER,'score_sound.wav'))\n",
    "score_sound.set_volume(0.2)\n",
    "\n",
    "class Dino(pygame.sprite.Sprite):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "        self.jump_sound = pygame.mixer.Sound(os.path.join(THIS_FOLDER,'jump_sound.wav'))\n",
    "        self.death_sound = pygame.mixer.Sound(os.path.join(THIS_FOLDER, 'death_sound.wav'))\n",
    "        \n",
    "        self.up = False\n",
    "        self.stop = False\n",
    "        self.xpos = 50\n",
    "        self.ypos = (SCREEN_HEIGHT // 2) + 140\n",
    "        self.dino_imgs = [os.path.join(THIS_FOLDER,f'dinossaur{i}.png') for i in range(3)]\n",
    "\n",
    "        self.index = 0\n",
    "        self.image = pygame.image.load(self.dino_imgs[self.index]).convert_alpha()\n",
    "        self.mask = pygame.mask.from_surface(self.image)\n",
    "\n",
    "        self.image = pygame.transform.scale(self.image, (84, 84))\n",
    "        self.rect = self.image.get_rect()\n",
    "        self.rect[0], self.rect[1] = self.xpos, self.ypos\n",
    "    \n",
    "    def collision(self):\n",
    "        global GAME_SPEED, FLOOR_SPEED\n",
    "        if pygame.sprite.spritecollide(dino, obstacle_group, False, pygame.sprite.collide_mask) or pygame.sprite.spritecollide(dino, flying_dino_group, False, pygame.sprite.collide_mask):\n",
    "            GAME_SPEED = 0\n",
    "            FLOOR_SPEED = 0\n",
    "            self.stop = True\n",
    "            flying_dino.stop = True\n",
    "            \n",
    "    def jump(self):\n",
    "        self.jump_sound.play()\n",
    "        self.up = True\n",
    "        \n",
    "    def update(self):\n",
    "        #JUMP CONDITION\n",
    "        if self.stop == False:\n",
    "            if self.up == False:\n",
    "                if self.rect[1] < self.ypos:\n",
    "                    self.rect[1] += 20\n",
    "                else:\n",
    "                    self.rect[1] = self.ypos\n",
    "            if self.up == True:\n",
    "                if self.rect[1] <= self.ypos - 200:\n",
    "                    self.up = False\n",
    "                else:\n",
    "                    self.rect[1] -= 30\n",
    "        \n",
    "            #SPRITES\n",
    "            if self.index >= len(self.dino_imgs) - 1:\n",
    "                self.index = 0\n",
    "            self.index += 0.25\n",
    "\n",
    "            self.image = pygame.image.load(self.dino_imgs[int(self.index)]).convert_alpha()\n",
    "            self.image = pygame.transform.scale(self.image, (128, 128))\n",
    "            self.mask = pygame.mask.from_surface(self.image)\n",
    "\n",
    "        else:\n",
    "            pass\n",
    "\n",
    "class Flying_dino(pygame.sprite.Sprite):\n",
    "    def __init__(self):\n",
    "        super().__init__()        \n",
    "        self.flying_dino_imgs = [os.path.join(THIS_FOLDER, f'fly_dino{i}.png') for i in range(2)]\n",
    "        self.stop = False\n",
    "        self.index = 0\n",
    "        self.image = pygame.image.load(self.flying_dino_imgs[self.index]).convert_alpha()\n",
    "        self.mask = pygame.mask.from_surface(self.image)\n",
    "        \n",
    "        self.image = pygame.transform.scale(self.image, (84, 84))\n",
    "        self.rect = self.image.get_rect()\n",
    "        self.rect[0], self.rect[1] = SCREEN_WIDTH, (SCREEN_HEIGHT // 2) \n",
    "\n",
    "    def update(self):\n",
    "        #SPRITES\n",
    "        if self.stop == False:\n",
    "            if self.index >= len(self.flying_dino_imgs) - 1:\n",
    "                self.index = 0\n",
    "\n",
    "            self.index += 0.25\n",
    "            self.image = pygame.image.load(self.flying_dino_imgs[int(self.index)]).convert_alpha()\n",
    "            self.image = pygame.transform.scale(self.image, (128, 128))\n",
    "            self.mask = pygame.mask.from_surface(self.image)\n",
    "        else:\n",
    "            pass\n",
    "\n",
    "class Obstacle(pygame.sprite.Sprite):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "        self.obstacle_imgs = [os.path.join(THIS_FOLDER,'obstacle0.png')]\n",
    "\n",
    "        self.image = pygame.image.load(self.obstacle_imgs[0]).convert_alpha()\n",
    "        self.mask = pygame.mask.from_surface(self.image)\n",
    "        self.image = pygame.transform.scale(self.image, (84, 84))\n",
    "        self.rect = self.image.get_rect()\n",
    "        self.rect[0], self.rect[1] = SCREEN_WIDTH, (SCREEN_HEIGHT // 2) + 162\n",
    "        self.mask = pygame.mask.from_surface(self.image)\n",
    "\n",
    "class Clouds(pygame.sprite.Sprite):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "        self.cloud_imgs = [os.path.join(THIS_FOLDER,'clouds0.png')]\n",
    "\n",
    "        self.image = pygame.image.load(self.cloud_imgs[0]).convert_alpha()\n",
    "        self.image = pygame.transform.scale(self.image, (148, 148))\n",
    "        self.rect = self.image.get_rect()\n",
    "        self.rect[0], self.rect[1] = (SCREEN_WIDTH // 2) + randrange(-400, 400, 100) , (SCREEN_HEIGHT // 2) - randrange(200, 400, 100)\n",
    "    \n",
    "    def update(self):\n",
    "        if self.rect.topright[0] < 0:\n",
    "            self.rect[0] = SCREEN_WIDTH\n",
    "            self.rect[1] = (SCREEN_HEIGHT // 2) - randrange(200, 400, 100)\n",
    "        self.rect[0] -= GAME_SPEED\n",
    "\n",
    "class Floor(pygame.sprite.Sprite):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "        self.floor_imgs = [os.path.join(THIS_FOLDER,'floor0.png')]\n",
    "\n",
    "        self.image = pygame.image.load(self.floor_imgs[0]).convert_alpha()\n",
    "        self.image = pygame.transform.scale(self.image, (64, 64))\n",
    "        self.rect = self.image.get_rect()\n",
    "        self.rect[0], self.rect[1] = 0 , SCREEN_HEIGHT // 2  + 200\n",
    "    def update(self):\n",
    "        if self.rect.topright[0] < 0:\n",
    "            self.rect[0] = SCREEN_WIDTH\n",
    "        self.rect[0] -= FLOOR_SPEED\n",
    "\n",
    "dino = Dino()\n",
    "dino_group = pygame.sprite.Group()\n",
    "dino_group.add(dino)\n",
    "\n",
    "flying_dino = Flying_dino()\n",
    "flying_dino_group = pygame.sprite.Group()\n",
    "flying_dino_group.add(flying_dino)\n",
    "\n",
    "obstacle = Obstacle()\n",
    "obstacle_group = pygame.sprite.Group()\n",
    "obstacle_group.add(obstacle)\n",
    "\n",
    "numb_of_clouds = 5\n",
    "clouds_group = pygame.sprite.Group()\n",
    "for c in range(numb_of_clouds):\n",
    "    clouds = Clouds()\n",
    "    clouds_group.add(clouds)\n",
    "\n",
    "floor_group = pygame.sprite.Group()\n",
    "for c in range(-64, SCREEN_WIDTH, 60):\n",
    "    floor = Floor()\n",
    "    floor.rect[0] = c\n",
    "    floor_group.add(floor)\n",
    "\n",
    "clock = pygame.time.Clock()\n",
    "\n",
    "obstacle_choice = choice([obstacle, flying_dino])\n",
    "\n",
    "while True:\n",
    "    sucess, img = cap.read()\n",
    "    \n",
    "    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
    "    imgCanny = cv2.Canny(gray, 155, 105)\n",
    "        \n",
    "    model_prediction = convert_frame_to_model(imgCanny)\n",
    "        \n",
    "    if model_prediction == 0:\n",
    "        msg = 'Not jumping'\n",
    "    else:\n",
    "        msg = 'Jumping'\n",
    "            \n",
    "    cv2.putText(imgCanny, f'{msg}', (480//2, 50), cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),3) #msg, origin, font, scale_font, color, thickness\n",
    "    cv2.imshow('Canny', imgCanny)\n",
    "                \n",
    "    if cv2.waitKey(1) & 0xff == ord('q'):\n",
    "        break\n",
    "    \n",
    "    clock.tick(FPS)\n",
    "    screen.fill(WHITE)\n",
    "\n",
    "    for event in pygame.event.get():\n",
    "        if event.type == pygame.QUIT:\n",
    "            pygame.quit()\n",
    "            exit()\n",
    "\n",
    "        if event.type == pygame.KEYDOWN:\n",
    "            if event.key == pygame.K_q:\n",
    "                cap.release()\n",
    "                cv2.destroyAllWindows()\n",
    "                pygame.quit()\n",
    "                exit()\n",
    "                '''\n",
    "                if event.key == pygame.K_SPACE:\n",
    "                    if dino.rect[1] < dino.ypos:\n",
    "                        pass\n",
    "                    else:\n",
    "                        dino.jump()\n",
    "                '''\n",
    "            if event.key == pygame.K_r and GAME_OVER == True:\n",
    "                GAME_SPEED = 10\n",
    "                FLOOR_SPEED = 10\n",
    "                points = 0\n",
    "                song = 0\n",
    "                obstacle.rect[0] = SCREEN_WIDTH\n",
    "                flying_dino.rect[0] = SCREEN_WIDTH\n",
    "                dino.stop = False\n",
    "                dino.rect[1] = dino.ypos\n",
    "                flying_dino.stop = False\n",
    "\n",
    "    dino_group.draw(screen)\n",
    "    dino_group.update()\n",
    "    dino.collision()\n",
    "\n",
    "    flying_dino_group.draw(screen)\n",
    "    flying_dino_group.update()\n",
    "\n",
    "    obstacle_group.draw(screen)\n",
    "    obstacle_group.update()\n",
    "\n",
    "    clouds_group.draw(screen)\n",
    "    clouds_group.update()\n",
    "\n",
    "    floor_group.draw(screen)\n",
    "    floor_group.update()\n",
    "\n",
    "    text = font.render(f'{points}', True, BLACK)\n",
    "    screen.blit(text, (700, 40))\n",
    "    \n",
    "    if model_prediction == 1:\n",
    "        if dino.rect[1] < dino.ypos:\n",
    "            pass\n",
    "        else:\n",
    "            dino.jump()\n",
    "\n",
    "    if obstacle_choice.rect.topright[0] < 0:\n",
    "        flying_dino.rect[0] = SCREEN_WIDTH\n",
    "        obstacle.rect[0] = SCREEN_WIDTH\n",
    "        obstacle_choice = choice([obstacle, flying_dino])\n",
    "    else:\n",
    "        obstacle_choice.rect[0] -= GAME_SPEED\n",
    "\n",
    "    if GAME_SPEED != 0:\n",
    "        points += 1\n",
    "        if (points % 100) == 0:\n",
    "            score_sound.play()\n",
    "            if GAME_SPEED == 46:\n",
    "                pass\n",
    "            else:\n",
    "                GAME_SPEED += 2\n",
    "    else:\n",
    "        points += 0\n",
    "        if song > 1:\n",
    "            song = 2\n",
    "        else:\n",
    "            song += 1\n",
    "        dino.jump_sound.stop()\n",
    "        txt = ['GAME OVER', 'Press R to play again']\n",
    "        line1 = font.render(txt[0], True, BLACK)\n",
    "        line2 = font.render(txt[1], True, BLACK)\n",
    "        screen.blit(line1, ((SCREEN_WIDTH // 2) - (line1.get_width()//2), (SCREEN_HEIGHT // 2) - 100))\n",
    "        screen.blit(line2, ((SCREEN_WIDTH // 2) - (line2.get_width()//2), (SCREEN_HEIGHT // 2) - 50))\n",
    "        GAME_OVER = True\n",
    "\n",
    "    if song == 1:\n",
    "        dino.death_sound.play()\n",
    "\n",
    "    pygame.display.flip()\n",
    "\n",
    "#Release everything if job is finished\n",
    "cap.release()\n",
    "cv2.destroyAllWindows()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
